<?php

namespace app\index\service;

use app\common\model\Consulting;
use app\common\model\Member;
use app\common\service\TemplateSmsService;
use app\index\dao\ConsultingDao;
use app\index\model\UM as UM;
use ShidianUtil\Utils\CheckUtil;
use think\Collection;
use think\exception\ValidateException;

/**
 * Class ConsultingService
 * @package app\consulting\service
 */
class ConsultingService
{
    // dao
    private ConsultingDao $consultingDao;

    public function __construct(ConsultingDao $consultingDao)
    {
        $this->consultingDao = $consultingDao;
    }

    /**
     * 获取咨询列表
     * @param \app\index\model\UM $user
     * @param array $params
     * @return Collection
     */
    public function index(UM $user, array $params): Collection
    {
        $page = $params['page'] ?? null;
        $page_size = $params['page_size'] ?? null;

        if ($user->type == '1') {
            $collection = $this->consultingDao->selectChatsOfLawyer($user->id, $page, $page_size);
        } else {
            $collection = $this->consultingDao->selectChatsOfMember($user->id, $page, $page_size);
        }

        // 最新一条消息，包装动态消息
        $messages = collection_field_collect($collection, 'lastMessage');

        $this->getMessageContentService()->wrapDynamicMessages($messages);

        return $collection;
    }

    /**
     * 律师工作台-待处理咨询
     * @param UM $user
     * @param $page
     * @param $page_size
     * @return Collection
     */
    public function indexWorkbench(UM $user, $consultingServerId, $page, $page_size): Collection
    {
        return $this->consultingDao->selectWorkbench($user->id, $consultingServerId, $page, $page_size);
    }

    /**
     * 查询
     * @param \app\index\model\UM|null $user
     * @param int $id
     * @return Consulting
     */
    public function read(UM $user, int $id): ?Consulting
    {
        $record = $this->consultingDao->findOfChat($id);

        // 前端需要判断自己是什么
        if ($record) {

            $record->chatMemberType = $user ? $user->type : null;

        }

        $remind = $this->getConsultingServerCheckService()->read($id);
        foreach ($remind as $k => $value) {
            $record->$k = $value;
        }

        return $record;
    }

    /**
     * 确认已抢咨询
     * @param UM $user
     * @param int $id
     * @return void
     */
    public function confirm(UM $user, int $id): void
    {
        $lawyerId = $user->id;

        // 同步
        $record = Consulting::where('id', $id)->find();
        if (!$record) {
            throw new ValidateException('该咨询不存在或已被删除');
        }

        if ($record->lawyerId != $user->id) {
            throw new ValidateException('该咨询已重新分配');
        }

        if ($record->rushStatus == 2) {
            return;
        }

        $success = $this->getConsultingLawyerMatchService()->confirm($record, $lawyerId);

        // 触发咨询变动事件（更新前端的咨询模型）
        if ($success) {
            event('ConsultingUpdated', $record);

            $memberId = $record->memberId;
            if (is_id($memberId)) {
                $phone = Member::where('id', $memberId)->value('phone');
                if (CheckUtil::isPhoneNumber($phone)) {
                    $this->getTemplateSmsService()->rushRemind($phone);
                }
            }
        }
    }

    private function getMessageContentService(): MessageContentService
    {
        return app(MessageContentService::class);
    }

    private function getConsultingServerCheckService(): ConsultingServerCheckService
    {
        return app(ConsultingServerCheckService::class);
    }

    private function getConsultingLawyerMatchService(): ConsultingLawyerMatchService
    {
        return app(ConsultingLawyerMatchService::class);
    }

    private function getTemplateSmsService(): TemplateSmsService
    {
        return app(TemplateSmsService::class);
    }
}
